// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
const { result } = require('product-api-utils');
const db = uniCloud.database();
const dbCmd = db.command;
let clientIp;

module.exports = {
	_before: function () {
		// 通用预处理器
		this.startTime = Date.now();
		this.params = {};
		const httpInfo = this.getHttpInfo();
		if (httpInfo) {
			const body = httpInfo.body;
			if (!body) throw result(400, 'required', 'body不能为空！');
			this.params = JSON.parse(body);
			clientIp = httpInfo.headers['x-real-ip'];
		}
	},

	// 获取文章列表
	async list() {
		let { pageSize = 8, pageNum = 0, delStatus = false } = this.params;
		const res = await db
			.collection('product_article')
			.where({
				delstatus: dbCmd.eq(delStatus)
			})
			.limit(pageSize)
			.skip(pageNum)
			.orderBy('posttime', 'desc')
			.get();
		return result(0, 'success', res.data);
	},

	// 获取文章详情
	async detail() {
		let { id } = this.params;
		if (!id) return result(400, 'required', 'id不能为空！');
		let res = await db.collection('product_article').doc(id).get();
		return result(0, 'success', res.data);
	},

	// 新增文章
	async add() {
		let { title, author, content, picurls, delstatus = false } = this.params;
		if (!title || !author || !content) return result(400, 'required', 'title、author、content不能为空！');
		const res = await db.collection('product_article').add({
			addip: clientIp,
			posttime: Date.now(),
			picurls,
			title,
			author,
			content,
			delstatus
		});
		return result(0, 'success', res);
	},

	// 更新文章
	async update() {
		let { id, title, author, content, picurls } = this.params;
		if (!id) return result(400, 'required', 'id不能为空！');
		const res = await db
			.collection('product_article')
			.doc(id)
			.update({
				updateip: dbCmd.push(clientIp),
				title: title,
				author: author,
				content: content,
				picurls
			});
		return result(0, 'success', res);
	},

	// 删除文章
	async remove() {
		let { id } = this.params;
		if (!id) return result(400, 'required', 'id不能为空！');
		const res = await db
			.collection('product_article')
			.doc(id)
			.update({
				delstatus: true,
				delip: dbCmd.push(clientIp)
			});
		return result(0, 'success', res);
	},

	_after: function (error, result) {
		if (error) {
			throw error; // 如果方法抛出错误，也直接抛出不处理
		}
		result.timeCost = Date.now() - this.startTime;
		result.author = '接口提供者：明致成';
		return result;
	}
};
